from enum import Enum
from typing import Optional
import time
from datetime import datetime

class LogLevel(Enum):
    """日志级别"""
    ERROR = 'error'
    SUCCESS = 'success'
    INFO = 'info'
    WARNING = 'warning'

class Logger:
    """日志管理器"""
    
    # ANSI颜色代码
    _COLORS = {
        LogLevel.ERROR: '\033[91m',   # 红色
        LogLevel.SUCCESS: '\033[92m',  # 绿色
        LogLevel.INFO: '\033[96m',     # 青色
        LogLevel.WARNING: '\033[93m'   # 黄色
    }
    _RESET_COLOR = '\033[0m'
    
    @classmethod
    def log(cls, message: str, level: LogLevel = LogLevel.INFO, show_time: bool = True) -> None:
        """
        输出日志
        
        Args:
            message: 日志消息
            level: 日志级别
            show_time: 是否显示时间
        """
        # 获取当前时间
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') if show_time else ''
        time_str = f"[{current_time}] " if show_time else ''
        
        # 获取颜色
        color = cls._COLORS.get(level, '')
        
        # 打印到控制台
        print(f"{color}{time_str}[{level.value.upper()}] {message}{cls._RESET_COLOR}")
    
    @classmethod
    def error(cls, message: str, show_time: bool = True) -> None:
        """错误日志"""
        cls.log(message, LogLevel.ERROR, show_time)
    
    @classmethod
    def success(cls, message: str, show_time: bool = True) -> None:
        """成功日志"""
        cls.log(message, LogLevel.SUCCESS, show_time)
    
    @classmethod
    def info(cls, message: str, show_time: bool = True) -> None:
        """信息日志"""
        cls.log(message, LogLevel.INFO, show_time)
    
    @classmethod
    def warning(cls, message: str, show_time: bool = True) -> None:
        """警告日志"""
        cls.log(message, LogLevel.WARNING, show_time)

# 创建全局日志实例
logger = Logger()

def log_message(message: str, level: str = 'info', show_time: bool = True) -> None:
    """
    向后兼容的日志函数
    
    Args:
        message: 日志消息
        level: 日志级别 ('error', 'success', 'info', 'warning')
        show_time: 是否显示时间
    """
    try:
        log_level = LogLevel(level)
        logger.log(message, log_level, show_time)
    except ValueError:
        logger.warning(f"未知的日志级别: {level}，使用默认级别(INFO)")
        logger.info(message, show_time)